//
//  SafeAreaListViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/16.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SafeAreaListViewController.h"
#import "SetSafeAreaViewController.h"
#import "AppDelegate.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "Watch.h"
@interface SafeAreaListViewController ()
@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,weak) AppDelegate *mydelegate;
@property (nonatomic,retain) User *user;
@property (nonatomic,retain) NSArray *tempArray;
@end

@implementation SafeAreaListViewController
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize safeAreaTableView;
@synthesize safeAreaTableViewCell;
@synthesize addSafeAreaTableViewCell;
//@synthesize safeDetailsDataArray;
@synthesize safeTableViewHeight;
@synthesize nameMap;
@synthesize tipsLabelContrain;
-(void)dealloc
{
    safeAreaTableViewCell=NULL;
    addSafeAreaTableViewCell=NULL;
    nameMap=NULL;
    self.dataManager=NULL;
    self.syncManager=NULL;
    self.user=NULL;
    self.tempArray=NULL;
    [self.mydelegate.safeDetailsDataArray removeAllObjects];
    self.mydelegate.safeDetailsDataArray=NULL;
    self.mydelegate=NULL;
}
- (void)viewDidLoad {
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    self.mydelegate.safeDetailsDataArray = [[NSMutableArray alloc]init];
    nameMap = [NSArray arrayWithObjects:@"学校",@"家",@"公司",@"其他",nil];
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title = @"安全区域";
    [self initNavButton];
    [self worktable];
    [self initDataProxy];
    // Do any additional setup after loading the view from its nib.
//    if(self.mydelegate.isAdmin == NO)
//    {
//        self.navigationItem.rightBarButtonItem = nil;
//    }
    self.navigationItem.rightBarButtonItem = nil;

    if(self.user == NULL)
        return;
    Watch *selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    if(self.syncManager!=NULL)
    {
        [self.syncManager getGeoFences:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result == SUCESS)
            {
                [self initData];
                [safeAreaTableView reloadData];
                if (self.mydelegate.safeDetailsDataArray.count==0)
                {
                    //[LeoMsg showMsg:@"宝宝离开进入时会给您发送通知"];
                }

            }
        }];
    }
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [self initData];
    [safeAreaTableView reloadData];
//    if (self.mydelegate.safeDetailsDataArray.count==3)
//    {
//        tipsLabelContrain.constant=-80;
//    }
    safeTableViewHeight.constant=[self findTableHeight_2];
    [self.view setNeedsLayout];

}

-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
    self.user = [User sharedSingleton];
}

-(void)initData{
    NSString *userId=self.user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    [self.mydelegate.safeDetailsDataArray removeAllObjects];
    NSArray *safeArray=[self.dataManager getFenceList:watchId];
    for (int i=0;i<safeArray.count;i++)
    {
        Fence *fence=[safeArray objectAtIndex:i];
        NSString *activeString;
        if (fence.is_active){
            activeString=@"1";
        }
        else{
            activeString=@"0";
        }
        NSString *name=@"其他";
        if(fence!=NULL&&fence.type==1)
        {
            name=@"学校";
        }
        else if(fence!=NULL&&fence.type==2)
        {
            name=@"家";
        }
        else if(fence!=NULL&&fence.type==3)
        {
            if(fence.title!=NULL&&![fence.title isEqualToString:@"(null)"]&&![fence.title isEqualToString:@""])
                name=fence.title;
        }
        else if(fence!=NULL&&fence.type==100)
        {
            if(fence.title!=NULL&&![fence.title isEqualToString:@"(null)"]&&![fence.title isEqualToString:@""])
                name=fence.title;
        }
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:name,@"name",[NSString stringWithFormat:@"%.0f",fence.radius],@"radius",activeString,@"status",fence.fence_id,@"fenceID",fence.desc,@"position",nil];
        
        [self.mydelegate.safeDetailsDataArray addObject:dic];
    }
}

// just for test
-(void)callback:(SyncResult) result retValue:(NSDictionary *)ret description:(NSString *)description
{
    
    if(result==SUCESS)
    {
        NSLog(@"sync result is sucess");
    }
    else
    {
        NSLog(@"sync fail,error is %@",description);
    }
}

-(void)worktable{
    self.automaticallyAdjustsScrollViewInsets=NO;
    safeAreaTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    safeAreaTableView.scrollEnabled=NO;
    safeAreaTableView.rowHeight = UITableViewAutomaticDimension;
    safeAreaTableView.delegate=self;
    safeAreaTableView.dataSource=self;
    
    UINib *cellsafe = [UINib nibWithNibName:@"SafeAreaTableViewCell" bundle:nil];
    [safeAreaTableView registerNib:cellsafe forCellReuseIdentifier:@"safeAreaCell"];
    self.safeAreaTableViewCell  = [safeAreaTableView dequeueReusableCellWithIdentifier:@"safeAreaCell"];
    
    UINib *cellAdd = [UINib nibWithNibName:@"AddSafeAreaTableViewCell" bundle:nil];
    [safeAreaTableView registerNib:cellAdd forCellReuseIdentifier:@"addSafeAreaCell"];
    self.addSafeAreaTableViewCell  = [safeAreaTableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
    
}

-(void)switchAction:(UISwitch*)sender
{
    int x=sender.tag-100;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSMutableDictionary *dicOne=[myDelegate.safeDetailsDataArray objectAtIndex:x];
    NSString *fenceID=[dicOne valueForKey:@"fenceID"];
    Fence *fence=[self.dataManager getFence:fenceID];
    if (fence.is_active)
    {
        fence.is_active=NO;
    }
    else
    {
        fence.is_active=YES;
    }
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    [self.syncManager setGeoFence:watchId fence:fence completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if (result==SUCESS)
        {
            //TODO
            //[safeAreaTableView reloadData];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

- (void)initNavButton {
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.navigationItem.rightBarButtonItem = navRightButton;
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(deleteAction)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteAction{
    [self.safeAreaTableView setEditing:!self.safeAreaTableView.editing animated:YES];
    if (self.safeAreaTableView.editing)
    {
        [self.navRightButton setTitle:@"删除"];
    }
    else
    {
        [self.navRightButton setTitle:@"编辑"];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//////Override functions//////
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //SafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sageAreaCell"];
    //if ([LeoMsg convertToInt:]
    if (self.mydelegate.safeDetailsDataArray.count==0){return 80;}
    if(indexPath.row >self.mydelegate.safeDetailsDataArray.count-1){return 80;}
    if(indexPath.row >2){return 80;}

    float sum=80;
    NSDictionary *subdic=[self.mydelegate.safeDetailsDataArray objectAtIndex:indexPath.row];
    NSString *position= [NSString stringWithFormat:@"%@m,%@",[subdic objectForKey:@"radius"],[subdic objectForKey:@"position"]];
    //***详细地址
    if ([LeoMsg convertToInt:position]>15)
    {
        sum= sum+15*([LeoMsg convertToInt:position]/15);
    }
    //**地址名称
    NSString *postionName= [NSString stringWithFormat:@"%@",[subdic objectForKey:@"name"]];
    if ([LeoMsg convertToInt:postionName]>34)
    {
        sum=sum+25;;
    }

    
    //**地址名称
//    NSString *positionName= [NSString stringWithFormat:@"%@",[subdic objectForKey:@"name"]];
//    if ([LeoMsg convertToInt:position]>15)
//    {
//        sum= sum+15*([LeoMsg convertToInt:position]/15);
//    }

    return sum;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return safeDetailsDataArray.count+1;
    CGRect rect = [UIScreen mainScreen].bounds;
    //safeTableViewHeight.constant=[self findTableHeight];
    if(self.mydelegate.isAdmin==NO)
    {
//        if (80 * self.mydelegate.safeDetailsDataArray.count < rect.size.height) {
//            safeTableViewHeight.constant = 80 * self.mydelegate.safeDetailsDataArray.count;
//        }
//        else
//            safeTableViewHeight.constant = rect.size.height - 80;
        //if (self.mydelegate.safeDetailsDataArray.count>3){return 3;}
        return self.mydelegate.safeDetailsDataArray.count;
    }
    else
    {
//        if (80 * (self.mydelegate.safeDetailsDataArray.count+1) < rect.size.height) {
//            safeTableViewHeight.constant = 80 * (self.mydelegate.safeDetailsDataArray.count+1);
//        }
//        else
//            safeTableViewHeight.constant = rect.size.height - 80;
        //if (self.mydelegate.safeDetailsDataArray.count>=3){return 3;}
        return self.mydelegate.safeDetailsDataArray.count+1;
    }
    

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int x=0;
    if((indexPath.row == self.mydelegate.safeDetailsDataArray.count)&&(self.mydelegate.isAdmin)){
                AddSafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
        cell.navController=self.navigationController;
        cell=[self addCellLine:cell forIndex:indexPath.row];
        if (self.mydelegate.safeDetailsDataArray.count>=3)
        {
            cell.hidden=YES;
        }
        return cell;
    }
    SafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"safeAreaCell"];
    cell.navController=self.navigationController;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell = [cell getandSetData:[self.mydelegate.safeDetailsDataArray objectAtIndex:indexPath.row]];
    //Switch事件
    UISwitch *switchButton=[[UISwitch alloc]init];
    switchButton=(UISwitch *)cell.areaOnOff;
    switchButton.tag=100+[indexPath row];
    if(self.mydelegate.isAdmin==YES)
    {
        cell.areaOnOff.enabled=YES;
       [cell.areaOnOff addTarget:self action:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];
    }
    else
    {
        cell.areaOnOff.enabled=NO;
    }

    cell=[self addCellLine:cell forIndex:indexPath.row];
    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSArray *indexPaths = @[indexPath];
        //deleteRows++;
        //删除数据库里的数据
        User *user=[User sharedSingleton];
        NSString *userId=user.uid;
        Watch *watch=[self.dataManager getActiveWatch:userId];
        NSString *watchId=watch.deviceUid;
        NSMutableDictionary *dic=[myDelegate.safeDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *fenceID=[dic valueForKey:@"fenceID"];
        
        [self.syncManager deleteGeoFence:watchId fenceId:fenceID completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result==SUCESS){
                NSLog(@"成功！");
                [myDelegate.safeDetailsDataArray removeObjectAtIndex:[indexPath row]];  //删除数组里的数据
                [safeAreaTableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];  //删除对应数据的cell
                
                if (self.mydelegate.safeDetailsDataArray.count!=3)
                {
                    tipsLabelContrain.constant=0;
                }
                [tableView reloadData];
                safeTableViewHeight.constant=[self findTableHeight_2];
                [self.view setNeedsLayout];
            }
            else{
                NSLog(@"失败原因%@",description);
                [Tooler showHttpMsg:result description:description msg:@"删除安全区域失败"];

            }
        }];
        
    }
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (indexPath.row==myDelegate.safeDetailsDataArray.count) {
        return NO;
    }
    else
    {
        if(self.mydelegate.isAdmin)
            return YES;
        else
            return NO;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == self.mydelegate.safeDetailsDataArray.count){
        BaseMapViewController *setSafeAreaViewController = [[SetSafeAreaViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        setSafeAreaViewController.mapView = self.mydelegate.mapView;
        [self.navigationController pushViewController:setSafeAreaViewController animated:YES];
        [safeAreaTableView deselectRowAtIndexPath:indexPath animated:YES];
    }else{
        NSMutableDictionary *dic=[self.mydelegate.safeDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *fenceID=[dic valueForKey:@"fenceID"];
        Fence *fence = [self.dataManager getFence:fenceID];
        //NSDictionary *subdic=[[NSDictionary alloc]init];
        //subdic=[myDelegate.safeDetailsDataArray objectAtIndex:indexPath.row];
        BaseMapViewController *setSafeAreaViewController = [[SetSafeAreaViewController alloc]init];
        NSString *location=[dic valueForKey:@"position"];
        setSafeAreaViewController.orignalLocation=location;
        self.hidesBottomBarWhenPushed = YES;
        setSafeAreaViewController.fence = fence;
        [self.navigationController pushViewController:setSafeAreaViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
    }

}
//确定table高度
-(float)findTableHeight{
    float sum=0;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSArray *dic=myDelegate.safeDetailsDataArray;
    int max=dic.count;
    if(self.mydelegate.isAdmin){max=dic.count+1;}
    if (max>3){max=3;}
    float xLocation=80;
    for (int i=0;i<max;i++){
        int index=i;
        if(index >myDelegate.safeDetailsDataArray.count-1){xLocation=80;}
        else{
            if(index >2){xLocation=80;}
            else{
                if ((max==1)&&(self.mydelegate.isAdmin)){xLocation=80;}
                else{
                    NSDictionary *subdic=[myDelegate.safeDetailsDataArray objectAtIndex:index];
                    NSString *position= [NSString stringWithFormat:@"%@m,%@",[subdic objectForKey:@"radius"],[subdic objectForKey:@"position"]];
                    if ([LeoMsg convertToInt:position]>17)
                    {
                        xLocation=80+15*([LeoMsg convertToInt:position]/17);
                    }
                }
                
            }
        }
        sum=sum+xLocation;
    }
    return sum;
}
-(float)findTableHeight_2{
    float sum=0;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSArray *dic=myDelegate.safeDetailsDataArray;
    NSInteger max=dic.count;

    NSArray *cellArray=[safeAreaTableView visibleCells];
    for (int i=0;i<dic.count;i++){
        UITableViewCell *cell=cellArray[i];
        sum=sum+cell.frame.size.height;
    }
    if (max==3){
        sum=sum;
    }
    else{
        if(self.mydelegate.isAdmin){sum=sum+80;}
        
    }
    return sum;
}

-(UITableViewCell *)addCellLine:(UITableViewCell *)cell forIndex:(int)index{
    
        UILabel *orignal=[cell viewWithTag:999];
        if (orignal!=nil){
            [orignal removeFromSuperview];
        }

        NSArray *dic=self.mydelegate.safeDetailsDataArray;
        float xLocation=80;
        //if ([LeoMsg convertToInt:]
        if(index >self.mydelegate.safeDetailsDataArray.count-1){xLocation=80;}
        else{
            if(index >2){xLocation=80;}
            else{
                if ((index==0)&&(self.mydelegate.safeDetailsDataArray.count==0)) {xLocation=80;}
                else{
                    NSDictionary *subdic=[self.mydelegate.safeDetailsDataArray objectAtIndex:index];
                    NSString *position= [NSString stringWithFormat:@"%@m,%@",[subdic objectForKey:@"radius"],[subdic objectForKey:@"position"]];
                    NSString *postionName=[subdic objectForKey:@"name"];
                    if ([LeoMsg convertToInt:position]>15)
                    {
                        xLocation=80+15*([LeoMsg convertToInt:position]/15);
                    }
                    if ([LeoMsg convertToInt:postionName]>34)
                    {
                        xLocation=xLocation+25;;
                    }
                }
                
            }
        }
        
        UILabel *line;
        if ((index==dic.count)||(index>=2))
        {
            NSLog(@"有最后一条！");
            line=[[UILabel alloc]initWithFrame:CGRectMake(0, xLocation-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
        }
        else
        {
            if ((index==dic.count-1)&&(!self.mydelegate.isAdmin)){
                line=[[UILabel alloc]initWithFrame:CGRectMake(0, xLocation-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
            }else{
                line=[[UILabel alloc]initWithFrame:CGRectMake(20, xLocation-1, [UIScreen mainScreen].bounds.size.width-20, 1)];
            }
        }
        line.backgroundColor=[UIColor colorWithRed:226/255.0 green:226/255.0 blue:228/255.0 alpha:1.0];
    
        line.tag=999;

        [cell addSubview:line];
        
        return cell;

        
        
    
}

@end
